package com.tqz.zookeeper.rawapi.snowflakeid;

import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 雪花算法测试.
 *
 * @author <a href="https://github.com/tian-qingzhao">tianqingzhao</a>
 * @since 2025/9/5 14:52
 */
@Slf4j
public class SnowflakeIdTest {

    public static void main(String[] args) throws InterruptedException {
        // 创建worker节点
        long workerId = SnowflakeIdWorker.instance.getId();
        SnowflakeIdGenerator.instance.init(workerId);

        int threadCount = 10;

        ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);

        final HashSet<Long> idSet = new HashSet<>();
        Collections.synchronizedCollection(idSet);
        long start = System.currentTimeMillis();
        log.info(" start generate id ===");

        int turn = 50000;
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            threadPool.execute(() -> {
                for (long j = 0; j < turn; j++) {
                    long id = SnowflakeIdGenerator.instance.nextId();
                    synchronized (idSet) {
                        if (j % 10000 == 0) {
                            log.info("线程{}生成第{}个 id 为:{}",
                                    Thread.currentThread().getName(), j, id);
                        }
                        idSet.add(id);
                    }
                }
                countDownLatch.countDown();
            });
        }

        countDownLatch.await(50000, TimeUnit.MICROSECONDS);
        threadPool.shutdown();
        threadPool.awaitTermination(10, TimeUnit.SECONDS);

        long end = System.currentTimeMillis();
        log.info("end generate id ===");
        log.info("* cost " + (end - start) + " ms!");
    }
}
